// modules =================================================
var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var multer = require('multer');
var compression = require('compression');
var morgan = require('morgan');
var fs = require('fs');

var mode = 'prod';
if (process.argv.length == 3 && process.argv[2] === 'dev') {
    mode = process.argv[2];
}

console.log('---------------------------------');
console.log('Start mode:', mode);
console.log('---------------------------------');


// set our port
var port = process.env.PORT || 8080;

// connect to our mongoDB database
var mongoose = require('mongoose');

var db = mongoose.connect('mongodb://localhost/promocast', function (err) {
    if (err) {
        console.error(chalk.red('Could not connect to MongoDB!'));
        console.log(chalk.red(err));
    } else {
        console.log('Connection successful to MongoDB');
    }
});

mongoose.connection.on('error', function (err) {
    console.error(chalk.red('MongoDB connection error: ' + err));
    process.exit(-1);
});

// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(multer({
    inMemory: true
}));

app.disable('x-powered-by');
app.disable('etag');


// Cache control
app.get('/', function (req, res, next) {
    res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');

    next();
});


//var auth = require('./app/auth');
//app.use(auth);

// set the static files location /public/img will be /img for users

if (mode === 'dev') {
    app.use(express.static(__dirname + '/public'));

} else {

    app.get('*.min.*.(js|css)', function (req, res, next) {
        res.setHeader('Cache-Control', 'public, max-age=31557600');

        next();
    });

    app.use(compression());

    var accessLogStream = fs.createWriteStream(__dirname + '/access.log', {
        flags: 'a'
    });

    app.use(morgan('common', {
        stream: accessLogStream
    }));


    app.use(express.static(__dirname + '/dist', {
        etag: false,
        lastModified: false
    }));



}

// routes ==================================================
app.all('/api/*', function (req, res, next) {
    res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
    next();
});

var contentRoute = require('./app/routes/content.route.js');
app.use('/api', contentRoute);


// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);

// shoutout to the user
console.log('PromoCast listens on port ' + port);

// expose app
exports = module.exports = app;
